package com.bullsora.kindlerss.web.mvc;

import com.bullsora.kindlerss.business.AppUserService;
import com.bullsora.kindlerss.model.AppUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.Principal;

/**
 * @author Sorin Buliarca
 */
@Component
public class PropagateCurrentUserFilter implements Filter {

  @Autowired
  private AppUserService appUserService;

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
      Principal currentPrincipal = ((HttpServletRequest) request).getUserPrincipal();
      if (currentPrincipal != null) {
        AppUser currentUser = appUserService.findUserByEmail(currentPrincipal.getName());
        if (currentUser != null) {
          AppUser.setCurrentUser(currentUser);
        }
      }
      chain.doFilter(request, response);      
    } finally {
      AppUser.clearCurrentUser();
    }

  }

  @Override
  public void destroy() {
  }
}
